<?php

namespace app\admin\controller\kuerp;

use app\common\controller\Backend;

/**
 * {:__('AREA_MANAGEMENT')}
 *
 * @icon fa fa-circle-o
 */
class Area extends Backend
{
    /**
     * Area模型对象
     * @var \app\admin\model\kuerp\Area
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $setData = (new Goods())->getSetData();
        $this->assign('set', $setData['setList']);
        $this->assignconfig('set', $setData['setList']);
        $this->assign('nowmenu', $setData['nowmenu']);

        $this->model = new \app\admin\model\kuerp\Area;
    }

    public function import()
    {
        parent::import();
    }

    /**
     * 获取省市区树结构
     */
    public function tree()
    {
        $list = $this->model->field('id,pid,name,level')
            ->order('level asc, pid asc, id asc')->select();
        $nodes = [];
        foreach ($list as $item) {
            $nodes[] = [
                'id' => (int)$item['id'],
                'pid' => (int)$item['pid'],
                'title' => $item['name'],
                'level' => (int)$item['level'],
            ];
        }
        // 构建 children 结构
        $idToNode = [];
        foreach ($nodes as &$n) { $n['children'] = []; $idToNode[$n['id']] = &$n; }
        $tree = [];
        foreach ($nodes as &$n) {
            if ($n['pid'] && isset($idToNode[$n['pid']])) {
                $idToNode[$n['pid']]['children'][] = &$n;
            } else {
                $tree[] = &$n;
            }
        }
        $this->success('', '', $tree);
    }

    /**
     * 根据 level-1 获取可选上级
     */
    public function parents()
    {
        $level = (int)$this->request->get('level', 0);
        if ($level <= 0) {
            $this->success('', '', []);
            return;
        }
        $list = $this->model->where('level', (int)$level)
            ->field('id,name,level,pid')->order('id asc')->select();
        $this->success('', '', $list);
    }
}


